package com.hy.codesandbox.util;

import com.hy.codesandbox.model.ExecuteMessage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created With IntelliJ IDEA.
 * Descriptions:进程工具类
 * User:Mr.Du
 * Date:2023/10/26
 * Time:21:10
 */
public class ProcessUtils {

    public static ExecuteMessage runProcessAndGetMessage(Process runProcess, String opName){
        ExecuteMessage executeMessage = new ExecuteMessage();

        try {
            int exitValue = runProcess.waitFor();
            executeMessage.setExitValue(exitValue);
            if(exitValue == 0){
                System.out.println(opName + "编译成功");
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
                StringBuilder compileOutputStringBuilder = new StringBuilder();
                String br;
                while((br = bufferedReader.readLine()) != null){
                    compileOutputStringBuilder.append(br);
                }
                executeMessage.setMessage(compileOutputStringBuilder.toString());
            }else{
                System.out.println(opName + "编译失败，错误码为: " + exitValue);
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(runProcess.getErrorStream()));
                StringBuilder compileOutputStringBuilder = new StringBuilder();
                String br;
                while((br = bufferedReader.readLine()) != null){
                    compileOutputStringBuilder.append(br);
                }
                executeMessage.setMessage(compileOutputStringBuilder.toString());

                BufferedReader errorBufferedReader = new BufferedReader(new InputStreamReader(runProcess.getErrorStream()));
                StringBuilder errorCompileOutputStringBuilder = new StringBuilder();
                String errorBr;
                while((errorBr = errorBufferedReader.readLine()) != null){
                    errorCompileOutputStringBuilder.append(errorBr);
                }
                executeMessage.setErrorMessage(errorCompileOutputStringBuilder.toString());
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return executeMessage;
    }
}
